<template>
  <div class="wrapper">
    <!-- header部分 -->
    <div class="head">
      <div class="head_left">
        <el-icon @click="back"><ArrowLeftBold /></el-icon>
      </div>
      <div class="head_right">
        <p>确认订单</p>
      </div>
    </div>
    <!-- 订单信息部分 -->
    <div class="order-info">
      <h5>订单配送至：</h5>
      <div class="order-info-address" @click="toUserAddress">
        <p>{{ data.deliveryaddress[0] ? data.deliveryaddress[0].address : '请选择送货地址' }}</p>
        <i class="fa fa-angle-right"></i>
      </div>
      <p>{{ data.user.userName }}{{ data.sex }} {{ data.user.userId }}</p>
    </div>
    <h3>{{ data.business.businessName }}</h3>
    <!-- 订单明细部分 -->
    <ul class="order-detailed">
      <li v-for="item in data.cartList" :key="item.food.foodId">
        <div class="order-detailed-left">
          <img :src="item.food.foodImg">
          <p>{{ item.food.foodName }} x {{ item.quantity }}</p>
        </div>
        <p>&#165;{{ item.food.foodPrice * item.quantity }}</p>
      </li>
    </ul>
    <div class="order-deliveryfee">
      <p>配送费</p>
      <p class="right">&#165;{{ data.business.deliveryPrice }}</p>
    </div>
    <!-- 合计部分 -->
    <div class="total">
      <div class="total-left">
        &#165;{{ data.totalPrice }}
      </div>
      <div class="total-right" @click="toPayment">
        去支付
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { useRoute } from 'vue-router';
import { useSessionStorage, useLocalStorage } from '@vueuse/core';
import request from "@/utils/request.js";
import { ElMessage } from "element-plus";
import router from "@/router";
import {ArrowLeftBold} from "@element-plus/icons-vue";



const data = reactive({
  business:{},
  deliveryaddress:{},
  cartList:{},
  businessId:0,
  user:JSON.parse(localStorage.getItem('user')),
  totalPrice:0, // 使用ref创建响应式变量
  sex:1,
  orderTypeId:1,
})

// 获取前面的商家id
const route = useRoute();
data.businessId = route.query.businessId;
data.orderTypeId = route.query.orderTypeId;

// 获取商家信息
const getBusiness= (businessId)=>{
  request.get(`/Business/getBusinessById/${businessId}`).then(res =>{
    if( res.code === 1){
      data.business= res.data
      //在调用
      listCart()
    }else {
      ElMessage.error(res.msg)

    }
  })

}


// 查询当前用户在购物车中的当前商家食品列表
const listCart=()=> {
  request.get('/Cart/listCart', {
        params: {
          userId:data.user.userId,
          businessId:data.businessId
        }
      }
  ).then(res => {
    if(res.code === 1){
      //把购物车信息给cartList
      data.cartList = res.data
    }else
    {
      ElMessage.error("出错啦！")
    }
  }).catch(error => {
    ElMessage.error("请求食品列表数据失败");
  });
}

// 查询地址
const getDeliveryAddress= (userId)=>{
  request.get('/DeliveryAddress/listDeliveryAddressByUserId',{
    params: {
      userId:userId
    }
  }).then(res =>{
    if( res.code === 1){
      data.deliveryaddress= res.data
    }else {

    }
  })

}


onMounted(async () => {
  getBusiness(data.businessId)
  getDeliveryAddress(data.user.userId)
  sexFilter(data.user.userSex)
});

// 观察cartList的变化来计算总价
watch(() => data.cartList, () => {
  const total = data.cartList.reduce((sum, cartItem) => {
    return sum + cartItem.food.foodPrice * cartItem.quantity;
  }, 0);
  data.totalPrice = total + data.business.deliveryPrice;
}, { immediate: false });



const sexFilter = (value) => {
  if (value === "1"){
    data.sex = '先生'
  }else {
    data.sex = '女士'
  }
};

//跳转到地址
const toUserAddress=()=> {
  router.push({ path: '/userAddress', query: { businessId: data.businessId } });
}

// 支付功能
const toPayment=()=> {
  if (data.deliveryaddress[0] === undefined) {
    alert('请选择送货地址！');
    return;
  }
  const order = {
    userId: data.user.userId,
    businessId: data.businessId,
    daId: data.deliveryaddress[0].daId,
    orderTotal: data.totalPrice
  }
  // 创建订单
  request.post('/Orders/createOrders', order).then(response => {
    const orderId = response.data;
    if (orderId > 0) {
      router.push({ path: '/payment', query: { orderId: orderId } });
    } else {
      alert('创建订单失败！');
    }
  }).catch(error => {
    console.error(error);
  });
}



const back =()=>{
  router.push({
    path: '/businessInfo',
    query: {
      businessId: data.businessId,
      orderTypeId: data.orderTypeId
    }
  });
}


</script>

<style scoped>
/* 总容器*/
.wrapper {
  width: 100%;
  height: 100%;
}
/* header部分 */
.wrapper .head {
  width: 100%;
  height: 12vw;
  background-color: #17BAF9;
  display: flex;
  justify-content: space-around;
  align-items: center;
  color: #fff;
  font-size: 4.8vw;
  position: fixed;
  left: 0;
  top: 0;
  /*保证在最上层*/
  z-index: 1000;
}

.wrapper .head .head_left{
  flex: 3;
  margin-left: 4vw;
  margin-top: 1vw;
}
.wrapper .head .head_right{
  flex: 6;
  margin-left: 2vw;
  font-size: 6vw;
}




/* 订单信息部分 */
.wrapper .order-info {
  /*注意这里，不设置高，靠内容撑开。因为地址有可能折行*/
  width: 100%;
  margin-top: 12vw;
  background-color: #0097EF;
  box-sizing: border-box;
  padding: 2vw;
  color: #fff;

}
.wrapper .order-info h5 {
  font-size: 3vw;
  font-weight: 300;
}
.wrapper .order-info .order-info-address {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 700;
  user-select: none;
  cursor: pointer;
  margin: 1vw 0;
}
.wrapper .order-info .order-info-address p {
  width: 90%;
  font-size: 5vw;
}
.wrapper .order-info .order-info-address i {
  font-size: 6vw;
}
.wrapper .order-info p {
  font-size: 4vw;
}
.wrapper h3 {
  box-sizing: border-box;
  padding: 3vw;
  font-size: 4vw;
  color: #666;
  border-bottom: solid 1px #DDD;
}
/* 订单明细部分 */
.wrapper .order-detailed {
  margin-left: 2vw;
  width: 100%;
}
.wrapper .order-detailed li {
  width: 100%;
  height: 16vw;
  box-sizing: border-box;
  padding: 3vw;
  color: #666;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.wrapper .order-detailed li .order-detailed-left {
  display: flex;
  align-items: center;
}
.wrapper .order-detailed li .order-detailed-left img {
  width: 10vw;
  height: 10vw;
}
.wrapper .order-detailed li .order-detailed-left p {
  font-size: 3.5vw;
  margin-left: 2vw;
}
.wrapper .order-detailed li p {
  font-size: 3.5vw;
  margin-right: 6vw;
}
.wrapper .order-deliveryfee {
  margin-left: 3vw;
  width: 100%;
  height: 16vw;
  box-sizing: border-box;
  padding: 3vw;
  color: #666;
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 3.5vw;


}


.wrapper .order-deliveryfee .right{
  margin-right: 8vw;
}
/* 订单合计部分 */
.wrapper .total {
  width: 100%;
  height: 14vw;
  position: fixed;
  left: 0;
  bottom: 0;
  display: flex;
}
.wrapper .total .total-left {
  flex: 2;
  background-color: #505051;
  color: #fff;
  font-size: 4.5vw;
  font-weight: 700;
  user-select: none;
  display: flex;
  justify-content: center;
  align-items: center;
}
.wrapper .total .total-right {
  flex: 1;
  background-color: #38CA73;
  color: #fff;
  font-size: 4.5vw;
  font-weight: 700;
  user-select: none;
  cursor: pointer;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>